using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产工单_报工_工序.Process;
using ERP_SaaS_WinForm.物料管理;
using System.Linq;

namespace ERP_SaaS_WinForm.生产工单_报工_工序
{
    public partial class MaterialEditForm : Form
    {
        private DataGridView dgvSelectedMaterials;
        private Button btnSelectMaterials;
        private Button btnAdd;
        private Button btnCancel;
        private Label lblTitle;
        private Label lblSelectedMaterials;
        private int productionOrdersId;
        private List<ERP_SaaS_WinForm.物料管理.Material.MaterialInfoDto> selectedMaterials;

        public MaterialEditForm(int productionOrdersId)
        {
            this.productionOrdersId = productionOrdersId;
            this.selectedMaterials = new List<ERP_SaaS_WinForm.物料管理.Material.MaterialInfoDto>();
            InitializeComponent();
            InitializeForm();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // MaterialEditForm
            // 
            this.ClientSize = new System.Drawing.Size(1321, 616);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "MaterialEditForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "添加物料";
            this.ResumeLayout(false);

        }

        private void InitializeForm()
        {
            // 标题
            lblTitle = new Label
            {
                Text = "添加生产工单物料",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(20, 20),
                Size = new Size(300, 30),
                TextAlign = ContentAlignment.MiddleLeft
            };

            // 选择物料按钮
            btnSelectMaterials = new Button
            {
                Text = "选择物料",
                Location = new Point(20, 70),
                Size = new Size(120, 35),
                BackColor = Color.FromArgb(70, 130, 180),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                FlatStyle = FlatStyle.Flat
            };
            btnSelectMaterials.FlatAppearance.BorderSize = 0;
            btnSelectMaterials.Click += BtnSelectMaterials_Click;

            // 已选物料标签
            lblSelectedMaterials = new Label
            {
                Text = "已选物料:",
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(20, 130),
                Size = new Size(100, 25),
                TextAlign = ContentAlignment.MiddleLeft
            };

            // 已选物料列表
            dgvSelectedMaterials = new DataGridView
            {
                Location = new Point(20, 160),
                Size = new Size(540, 200),
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = false,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                RowHeadersVisible = false,
                BackgroundColor = Color.White,
                BorderStyle = BorderStyle.None,
                GridColor = Color.LightGray
            };

            // 设置表格样式
            dgvSelectedMaterials.DefaultCellStyle.SelectionBackColor = Color.FromArgb(230, 240, 250);
            dgvSelectedMaterials.DefaultCellStyle.SelectionForeColor = Color.Black;
            dgvSelectedMaterials.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
            dgvSelectedMaterials.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9, FontStyle.Bold);
            dgvSelectedMaterials.ColumnHeadersDefaultCellStyle.ForeColor = Color.FromArgb(64, 64, 64);
            dgvSelectedMaterials.ColumnHeadersHeight = 35;
            dgvSelectedMaterials.RowTemplate.Height = 30;

            // 添加列
            dgvSelectedMaterials.Columns.AddRange(new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn { Name = "序号", HeaderText = "序号", Width = 60 },
                new DataGridViewTextBoxColumn { Name = "物料编号", HeaderText = "物料编号", Width = 120 },
                new DataGridViewTextBoxColumn { Name = "物料名称", HeaderText = "物料名称", Width = 150 },
                new DataGridViewTextBoxColumn { Name = "规格型号", HeaderText = "规格型号", Width = 120 },
                new DataGridViewTextBoxColumn { Name = "单位", HeaderText = "单位", Width = 80 }
            });

            // 添加按钮
            btnAdd = new Button
            {
                Text = "添加",
                Location = new Point(400, 400),
                Size = new Size(80, 35),
                BackColor = Color.FromArgb(70, 130, 180),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                FlatStyle = FlatStyle.Flat
            };
            btnAdd.FlatAppearance.BorderSize = 0;
            btnAdd.Click += BtnAdd_Click;

            // 取消按钮
            btnCancel = new Button
            {
                Text = "取消",
                Location = new Point(500, 400),
                Size = new Size(80, 35),
                BackColor = Color.FromArgb(220, 53, 69),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                FlatStyle = FlatStyle.Flat
            };
            btnCancel.FlatAppearance.BorderSize = 0;
            btnCancel.Click += BtnCancel_Click;

            // 添加控件
            this.Controls.AddRange(new Control[]
            {
                lblTitle,
                btnSelectMaterials,
                lblSelectedMaterials,
                dgvSelectedMaterials,
                btnAdd,
                btnCancel
            });

            // 设置默认按钮
            this.AcceptButton = btnAdd;
            this.CancelButton = btnCancel;
        }

        private void BtnSelectMaterials_Click(object sender, EventArgs e)
        {
            try
            {
                var selectForm = new SelectMaterialForm();
                selectForm.AllowMultipleSelection = true;
                
                if (selectForm.ShowDialog(this) == DialogResult.OK)
                {
                    selectedMaterials = selectForm.SelectedMaterials;
                    DisplaySelectedMaterials();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择物料时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DisplaySelectedMaterials()
        {
            dgvSelectedMaterials.Rows.Clear();
            
            if (selectedMaterials == null || selectedMaterials.Count == 0)
            {
                lblSelectedMaterials.Text = "已选物料: 0";
                return;
            }

            for (int i = 0; i < selectedMaterials.Count; i++)
            {
                var material = selectedMaterials[i];
                var rowIndex = dgvSelectedMaterials.Rows.Add();
                
                dgvSelectedMaterials.Rows[rowIndex].Cells["序号"].Value = i + 1;
                dgvSelectedMaterials.Rows[rowIndex].Cells["物料编号"].Value = material.materialCode ?? "";
                dgvSelectedMaterials.Rows[rowIndex].Cells["物料名称"].Value = material.materialName ?? "";
                dgvSelectedMaterials.Rows[rowIndex].Cells["规格型号"].Value = material.specification ?? "";
                dgvSelectedMaterials.Rows[rowIndex].Cells["单位"].Value = material.unit ?? "";
            }

            lblSelectedMaterials.Text = $"已选物料: {selectedMaterials.Count}";
        }

        private async void BtnAdd_Click(object sender, EventArgs e)
        {
            if (selectedMaterials == null || selectedMaterials.Count == 0)
            {
                MessageBox.Show("请先选择要添加的物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                btnAdd.Enabled = false;
                btnAdd.Text = "添加中...";

                var success = await AddMaterialsAsync();
                if (success)
                {
                    MessageBox.Show($"成功添加 {selectedMaterials.Count} 个物料", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加物料时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnAdd.Enabled = true;
                btnAdd.Text = "添加";
            }
        }

        private async Task<bool> AddMaterialsAsync()
        {
            using (var httpClient = new HttpClient())
            {
                var request = new AddProductionMaterialCommand
                {
                    items = selectedMaterials.Select(m => new AddProductionMaterialRequest
                    {
                        productionOrdersId = this.productionOrdersId,
                        materialCode = m.materialCode
                    }).ToArray()
                };

                var json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var url = "http://localhost:5257/api/ProductionMaterial/AddProductionMaterialCommand";
                var response = await httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<AddProductionMaterialApiResponse>(responseJson);

                    if (apiResponse.code == 200)
                    {
                        return apiResponse.data;
                    }
                    else
                    {
                        throw new Exception(apiResponse.message ?? "添加失败");
                    }
                }
                else
                {
                    throw new Exception($"网络请求失败: {response.StatusCode}");
                }
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
